#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：saas 
@File    ：account.py
@IDE     ：PyCharm 
@Author  ：janggui
@Date    ：2022/12/15 18:58 
'''
from django.conf import settings
from django import forms
from web import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import random
from utils.tencent.sms import send_sms_single
from django_redis import get_redis_connection


class RegisterForm(forms.ModelForm):
    mobile_phone = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput())
    confirm_password=forms.CharField(
        label='重复密码',
        widget=forms.PasswordInput())
    code=forms.CharField(
        label='验证码',
        widget=forms.TextInput())

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


class SendSmsForm(forms.Form):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])

    # 重写父类
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    # 钩子函数校验数据库

    def clean_mobile_phone(self):

        mobile_phone = self.cleaned_data['mobile_phone']

        # 检验短信模板是否有问题
        tpl = self.request.GET.get('tpl')
        template_id = settings.SMS_ID.get(tpl)

        if not template_id:
            raise ValidationError('短信模板错误！')

        # 校验手机号是否在数据库
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if exists:
            raise ValidationError('手机号已经存在！')
        # 发短信 写redis
        code = random.randrange(1000, 9999)
        sms = send_sms_single(mobile_phone, template_id, [code, ])
        if sms['result'] != 0:
            raise ValidationError("短信发送失败，{}".format(sms['errmsg']))

        # 验证码写入rides中,存在时间为120秒
        conn = get_redis_connection()
        conn.set(mobile_phone, code, ex=120)
        print("保存成功！")

        return mobile_phone





